<template>
    <NDrawer v-model:show="visible" width="80%" placement="right">
        <NDrawerContent title="审核" closable>
            <NDescriptions title="基础信息" label-placement="left">
                <NDescriptionsItem>
                    <template #label>UID</template>
                    {{ detail?.uid }}
                </NDescriptionsItem>
                <NDescriptionsItem>
                    <template #label>手机号</template>
                    {{ detail?.mobileNumber }}
                </NDescriptionsItem>
                <NDescriptionsItem>
                    <template #label>邮箱</template>
                    {{ detail?.email }}
                </NDescriptionsItem>
                <NDescriptionsItem>
                    <template #label>邀请码</template>
                    {{ detail?.inviteCode }}
                </NDescriptionsItem>
                <NDescriptionsItem>
                    <template #label>创建时间</template>
                    {{ detail?._createdAt }}
                </NDescriptionsItem>
                <NDescriptionsItem>
                    <template #label>推荐人</template>
                    {{ detail?.referrer }}
                </NDescriptionsItem>
                <NDescriptionsItem>
                    <template #label>卡余额</template>
                    {{ detail?.available }} HKD
                </NDescriptionsItem>
            </NDescriptions>
            <NDivider />
            <NDescriptions title="KYC证件" label-placement="left" :column="2">
                <NDescriptionsItem :span="2">
                    <template #label>证件类型</template>
                    {{ detail && CertificateType[detail?.certificateType] }}
                </NDescriptionsItem>
                <NDescriptionsItem :span="2">
                    <template #label>证件照片</template>
                    <NFlex>
                        <NImage width="200" :src="detail?.certificateImageFront" />
                        <NImage width="200" :src="detail?.certificateImageBack" />
                    </NFlex>
                </NDescriptionsItem>
                <NDescriptionsItem :span="1">
                    <template #label>证件号</template>
                    {{ detail?.certificateNumber }}
                </NDescriptionsItem>
                <NDescriptionsItem :span="1">
                    <template #label>证件有效期</template>
                    {{ detail?.certificateOfValidity }}
                </NDescriptionsItem>
            </NDescriptions>
            <NDivider />
            <DetailKyc :id="props.id" :detail="detail" />
            <NDivider />
            <NDescriptions title="付款信息" label-placement="left">
                <NDescriptionsItem>
                    <template #label>状态</template>
                    {{ detail?.paymentStatus === 1 ? '已支付' : '绑定卡' }}
                </NDescriptionsItem>
                <NDescriptionsItem>
                    <template #label>付款金额</template>
                    {{ detail?.paymentAmount }}
                </NDescriptionsItem>
            </NDescriptions>
            <NDivider />
            <NDescriptions title="卡信息" label-placement="top">
                <NDescriptionsItem v-if="detail">
                    <NTag size="small" :type="typeMap[detail.cardStatus]">
                        {{ MasterCardStatus[detail.cardStatus] }}
                    </NTag>
                    <div class="mt-2">
                        <NImage v-if="detail.cardImage" :src="detail.cardImage" :width="100"></NImage>
                    </div>

                    <template v-if="detail?.cardStatus === 6 || detail?.cardStatus === 7 || detail?.cardStatus === 9">
                        <div v-if="detail?.refusalReason" class="mt-2">
                            拒绝原因：<b>{{ detail.refusalReason }}</b>
                        </div>
                        <div class="mt-2">
                            客户预留卡号：<b>{{ detail?.cardNumber }}</b>
                        </div>
                        <div class="mt-2">如果指定卡号，请上传带有卡号的图片</div>
                        <Upload @updateList="fileListUpdate" :max="1" accept=".png, .jpg, .jpeg" />

                        <NFlex class="mt-2">
                            <NPopconfirm @negative-click="handleNegativeClick" @positive-click="handlePositiveClick">
                                <template #trigger>
                                    <NButton>拒绝</NButton>
                                </template>
                                <NForm ref="refuseForm" :model="form" :rules="rules" class="w-60">
                                    <NFormItem path="refusalReason">
                                        <NInput
                                            v-model:value="form.refusalReason"
                                            type="textarea"
                                            placeholder="请输入拒绝原因"
                                        />
                                    </NFormItem>
                                </NForm>
                            </NPopconfirm>
                            <NButton type="primary" @click="approve">通过</NButton>
                        </NFlex>
                    </template>
                </NDescriptionsItem>
            </NDescriptions>
        </NDrawerContent>
    </NDrawer>
</template>

<script setup lang="ts">
import { ref, watch, reactive } from 'vue'
import { useMessage, type FormInst } from 'naive-ui'
import { queryMasterCardDetail, updateMasterCardStatus } from '@/api/card'
import { CertificateType } from '@/constants/common'
import { MasterCardStatus } from '@/constants/card'
import dayjs from 'dayjs'
import DetailKyc from './DetailKyc.vue'
import Upload, { type UploadFileResponse } from '@/components/Upload.vue'

defineOptions({
    name: 'DetailDrawer'
})

const props = defineProps<{
    id: number | undefined
    item: Api.Card.MasterCardDetail | null
}>()
const emits = defineEmits<{
    refresh: []
}>()

const visible = defineModel<boolean>({
    required: true
})

const message = useMessage()

const typeMap: Record<Api.Card.MasterCardDetail['cardStatus'], Naive.Type> = {
    1: 'info',
    2: 'info',
    3: 'success',
    4: 'default',
    5: 'default',
    6: 'warning',
    7: 'error',
    8: 'default',
    9: 'warning'
}

const detail = ref<Api.Card.MasterCardDetail | null>(null)
const queryDetail = async () => {
    const [err, res] = await queryMasterCardDetail(props.id!)
    if (!err && res) {
        res._createdAt = dayjs(res.createdAt * 1000).format('YYYY-MM-DD')
        detail.value = res
        // if (props.item?.cardStatus) detail.value.cardStatus = props.item?.cardStatus
    }
}

watch(visible, newVal => {
    if (newVal) {
        queryDetail()
        form.refusalReason = ''
    }
})

const form = reactive({
    cardImage: '',
    requestId: '',
    refusalReason: ''
})

const rules = {
    refusalReason: {
        required: true,
        message: '请输入拒绝原因',
        trigger: 'blur'
    }
}

const refuseForm = ref<FormInst | null>(null)

const handleNegativeClick = () => {
    form.refusalReason = ''
}

const handlePositiveClick = () => {
    return refuseForm.value?.validate(errors => {
        if (errors) return false
        audit(4)
    })
}

const fileListUpdate = (fileList: UploadFileResponse[]) => {
    if (fileList.length) {
        const { requestId, imageUrl } = fileList[0].response!
        form.cardImage = imageUrl
        form.requestId = requestId
    } else {
        form.cardImage = ''
        form.requestId = ''
    }
}

const auditLoading = ref(false)
async function audit(status: Api.Card.MasterCardDetail['cardStatus']) {
    auditLoading.value = true
    const { refusalReason, ...opts } = form

    const [err, res] = await updateMasterCardStatus(props.id!, {
        status,
        ...(status === 4 ? { refusalReason, ...opts } : opts)
    })
    auditLoading.value = false
    if (!err && res) {
        message.success('操作成功')
        visible.value = false
        emits('refresh')
    }
}

function approve() {
    audit(3)
}
</script>
